package com.mudalov.rec.dao.hibernate.impl;

import com.mudalov.rec.dao.factory.DAOFactory;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.mudalov.rec.dao.hibernate.util.HibernateUtil;
import com.mudalov.rec.dao.interfaces.HbnGenericDAO;
import com.mudalov.rec.dao.interfaces.ITestDAO;
import com.mudalov.rec.dao.model.study.Question;
import com.mudalov.rec.dao.model.study.Subject;
import com.mudalov.rec.dao.model.study.Test;
import java.util.ArrayList;
import java.util.List;

public class HbnTestDAO extends HbnGenericDAO<Test, Long> implements
		ITestDAO {

	public HbnTestDAO(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Test createTest(String testName, Subject subject,
			Set<Question> questions) {
		Test test = new Test(testName, subject, questions);
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		session.save(test);
		tx.commit();
		session.close();
		return test;
	}

	@Override
	protected Class<Test> getEntityClass() {
		return Test.class;
	}

    @Override
    public List<Test> getTests(String name, String owner, String subject) {
        String query = "from Test t where t.owner.fullName like :ownerName " +
                "and t.name like :name " +
                "and t.subject.text like :subjectText";
        Session session = sessionFactory.openSession();
        List<Test> result = session.createQuery(query)
                .setString("name", "%" + name + "%")
                .setString("ownerName", "%" + owner + "%")
                .setString("subjectText", "%" + subject + "%").list();
        List<Test> detachedResult = new ArrayList<Test>();
        for (Test test : result) {
            detachedResult.add(test.getClone());
        }
        session.close();
        return detachedResult;
    }

    public static void main(String[] args) {
        ITestDAO testDAO = DAOFactory.getFactory(DAOFactory.HIBERNATE_MY_SQL).getTestDAO();
        List<Test> tests = testDAO.getTests("", "", "");
    }
}
